<template>
  <div class="alarm-records">
    <div class="page-header">
      <h1>桥梁系统报警记录</h1>
      <div class="header-actions">
        <t-date-range-picker
          v-model="dateRange"
          :presets="dateRangePresets"
          @change="handleDateRangeChange"
          style="margin-right: 16px"
        />
        <t-select
          v-model="alarmType"
          style="width: 150px; margin-right: 16px"
          placeholder="报警类型"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部类型" />
          <t-option value="振动异常" label="振动异常" />
          <t-option value="位移异常" label="位移异常" />
          <t-option value="温度异常" label="温度异常" />
          <t-option value="设备故障" label="设备故障" />
        </t-select>
        <t-select
          v-model="alarmLevel"
          style="width: 150px; margin-right: 16px"
          placeholder="报警等级"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部等级" />
          <t-option value="轻微" label="轻微" />
          <t-option value="一般" label="一般" />
          <t-option value="严重" label="严重" />
          <t-option value="紧急" label="紧急" />
        </t-select>
        <t-input
          v-model="searchText"
          placeholder="搜索报警信息"
          style="width: 200px"
          clearable
        >
          <template #suffix-icon>
            <t-icon name="search" @click="handleSearch" />
          </template>
        </t-input>
      </div>
    </div>

    <t-table
      :columns="columns"
      :data="filteredAlarms"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      bordered
      row-key="id"
    >
      <template #level="{ row }">
        <t-tag :theme="getAlarmLevelTheme(row.level)" variant="light">
          {{ row.level }}
        </t-tag>
      </template>
      <template #status="{ row }">
        <t-tag :theme="row.status === '已处理' ? 'success' : 'warning'" variant="light">
          {{ row.status }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <t-space>
          <t-link theme="primary" hover="color" @click="handleViewDetails(row)">查看详情</t-link>
          <t-link 
            theme="primary" 
            hover="color" 
            @click="handleProcessAlarm(row)" 
            v-if="row.status !== '已处理'"
          >
            处理报警
          </t-link>
          <span v-else>已处理</span>
        </t-space>
      </template>
    </t-table>

    <!-- 报警详情对话框 -->
    <t-dialog
      v-model:visible="detailsVisible"
      header="报警详情"
      :footer="false"
      width="700px"
    >
      <div v-if="currentAlarm" class="alarm-details">
        <t-descriptions bordered :column="2">
          <t-descriptions-item label="报警ID" :span="1">{{ currentAlarm.id }}</t-descriptions-item>
          <t-descriptions-item label="报警时间" :span="1">{{ currentAlarm.time }}</t-descriptions-item>
          <t-descriptions-item label="设备名称" :span="1">{{ currentAlarm.deviceName }}</t-descriptions-item>
          <t-descriptions-item label="设备位置" :span="1">{{ currentAlarm.deviceLocation }}</t-descriptions-item>
          <t-descriptions-item label="报警类型" :span="1">{{ currentAlarm.type }}</t-descriptions-item>
          <t-descriptions-item label="报警等级" :span="1">
            <t-tag :theme="getAlarmLevelTheme(currentAlarm.level)" variant="light">{{ currentAlarm.level }}</t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="报警状态" :span="1">
            <t-tag :theme="currentAlarm.status === '已处理' ? 'success' : 'warning'" variant="light">{{ currentAlarm.status }}</t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="处理人员" :span="1">{{ currentAlarm.handler || '-' }}</t-descriptions-item>
          <t-descriptions-item label="报警描述" :span="2">{{ currentAlarm.description }}</t-descriptions-item>
          <t-descriptions-item label="处理记录" :span="2">{{ currentAlarm.processRecord || '-' }}</t-descriptions-item>
        </t-descriptions>

        <div class="alarm-chart" v-if="currentAlarm.chartData">
          <h3>报警趋势图</h3>
          <!-- 这里可以添加图表组件，如 ECharts -->
          <div class="chart-placeholder">
            <p>此处可集成图表组件展示报警相关的数据趋势</p>
          </div>
        </div>

        <div class="action-buttons" v-if="currentAlarm.status !== '已处理'">
          <t-button theme="primary" @click="handleProcessCurrentAlarm">处理此报警</t-button>
        </div>
      </div>
    </t-dialog>

    <!-- 处理报警对话框 -->
    <t-dialog
      v-model:visible="processVisible"
      header="处理报警"
      :confirm-loading="confirmLoading"
      @confirm="confirmProcessAlarm"
    >
      <t-form
        ref="processFormRef"
        :data="processForm"
        :rules="rules"
        :label-width="80"
      >
        <t-form-item label="处理人" name="handler">
          <t-input v-model="processForm.handler" />
        </t-form-item>
        <t-form-item label="处理记录" name="processRecord">
          <t-textarea v-model="processForm.processRecord" :rows="4" />
        </t-form-item>
        <t-form-item label="处理结果" name="result">
          <t-select v-model="processForm.result">
            <t-option value="已解决" label="已解决" />
            <t-option value="暂时修复" label="暂时修复" />
            <t-option value="需进一步处理" label="需进一步处理" />
          </t-select>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import dayjs from 'dayjs';

// 表格列定义
const columns = [
  {
    colKey: 'id',
    title: '报警ID',
    width: '80',
  },
  {
    colKey: 'time',
    title: '报警时间',
    width: '180',
    sorter: true,
  },
  {
    colKey: 'deviceName',
    title: '设备名称',
    width: '150',
  },
  {
    colKey: 'type',
    title: '报警类型',
    width: '120',
  },
  {
    colKey: 'level',
    title: '报警等级',
    width: '100',
    cell: 'level',
  },
  {
    colKey: 'description',
    title: '报警描述',
    ellipsis: true,
  },
  {
    colKey: 'status',
    title: '状态',
    width: '100',
    cell: 'status',
  },
  {
    colKey: 'op',
    title: '操作',
    width: '150',
    cell: 'op',
  },
];

// 模拟数据
const alarms = ref([
  {
    id: '1001',
    time: '2023-09-15 08:23:45',
    deviceName: '振动传感器A1',
    deviceLocation: '主桥北侧',
    type: '振动异常',
    level: '严重',
    description: '主桥北侧振动传感器检测到异常振动，振幅超过安全阈值50%',
    status: '已处理',
    handler: '张工',
    processRecord: '现场检查发现由于大型车辆超载导致，已通知交警部门加强管控',
    chartData: true,
  },
  {
    id: '1002',
    time: '2023-09-16 14:35:12',
    deviceName: '位移传感器B2',
    deviceLocation: '主桥南侧',
    type: '位移异常',
    level: '一般',
    description: '主桥南侧位移传感器检测到轻微位移，但在安全范围内',
    status: '已处理',
    handler: '李工',
    processRecord: '现场检查确认为温度变化导致的正常伸缩，属于设计范围内',
    chartData: true,
  },
  {
    id: '1003',
    time: '2023-09-17 10:12:33',
    deviceName: '监控摄像头C1',
    deviceLocation: '桥梁入口',
    type: '设备故障',
    level: '轻微',
    description: '入口监控摄像头信号中断，可能存在设备故障',
    status: '未处理',
    handler: '',
    processRecord: '',
    chartData: false,
  },
  {
    id: '1004',
    time: '2023-09-18 16:45:22',
    deviceName: '温度传感器D3',
    deviceLocation: '主桥中段',
    type: '温度异常',
    level: '紧急',
    description: '主桥中段温度传感器检测到异常高温，可能存在安全隐患',
    status: '未处理',
    handler: '',
    processRecord: '',
    chartData: true,
  },
  {
    id: '1005',
    time: '2023-09-19 09:05:17',
    deviceName: '振动传感器A2',
    deviceLocation: '主桥中段',
    type: '振动异常',
    level: '一般',
    description: '主桥中段振动传感器检测到轻微振动异常，需要关注',
    status: '未处理',
    handler: '',
    processRecord: '',
    chartData: true,
  },
]);

// 状态变量
const loading = ref(false);
const searchText = ref('');
const alarmType = ref('');
const alarmLevel = ref('');
const dateRange = ref([]);
const detailsVisible = ref(false);
const processVisible = ref(false);
const confirmLoading = ref(false);
const currentAlarm = ref(null);
const processFormRef = ref(null);

// 处理表单
const processForm = reactive({
  handler: '',
  processRecord: '',
  result: '已解决',
});

// 表单验证规则
const rules = {
  handler: [{ required: true, message: '请输入处理人姓名', trigger: 'blur' }],
  processRecord: [{ required: true, message: '请输入处理记录', trigger: 'blur' }],
  result: [{ required: true, message: '请选择处理结果', trigger: 'change' }],
};

// 日期范围预设
const dateRangePresets = {
  '今天': [dayjs().startOf('day').toDate(), dayjs().endOf('day').toDate()],
  '本周': [dayjs().startOf('week').toDate(), dayjs().endOf('week').toDate()],
  '本月': [dayjs().startOf('month').toDate(), dayjs().endOf('month').toDate()],
  '最近7天': [dayjs().subtract(7, 'day').toDate(), dayjs().toDate()],
  '最近30天': [dayjs().subtract(30, 'day').toDate(), dayjs().toDate()],
};

// 根据筛选条件过滤报警记录
const filteredAlarms = computed(() => {
  let result = [...alarms.value];
  
  // 按日期范围筛选
  if (dateRange.value && dateRange.value.length === 2 && dateRange.value[0] && dateRange.value[1]) {
    const startDate = dayjs(dateRange.value[0]).startOf('day');
    const endDate = dayjs(dateRange.value[1]).endOf('day');
    result = result.filter(alarm => {
      const alarmDate = dayjs(alarm.time);
      return alarmDate.isAfter(startDate) && alarmDate.isBefore(endDate);
    });
  }
  
  // 按报警类型筛选
  if (alarmType.value) {
    result = result.filter(alarm => alarm.type === alarmType.value);
  }
  
  // 按报警等级筛选
  if (alarmLevel.value) {
    result = result.filter(alarm => alarm.level === alarmLevel.value);
  }
  
  // 按搜索文本筛选
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase();
    result = result.filter(alarm => 
      alarm.deviceName.toLowerCase().includes(keyword) ||
      alarm.description.toLowerCase().includes(keyword) ||
      alarm.type.toLowerCase().includes(keyword)
    );
  }
  
  return result;
});

// 获取报警等级对应的主题
const getAlarmLevelTheme = (level) => {
  switch (level) {
    case '紧急': return 'danger';
    case '严重': return 'warning';
    case '一般': return 'primary';
    case '轻微': return 'success';
    default: return 'default';
  }
};

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  // 日期范围变化的处理逻辑已通过计算属性实现
};

// 处理筛选条件变化
const handleFilterChange = () => {
  // 筛选条件变化的处理逻辑已通过计算属性实现
};

// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 查看报警详情
const handleViewDetails = (row) => {
  currentAlarm.value = { ...row };
  detailsVisible.value = true;
};

// 处理报警
const handleProcessAlarm = (row) => {
  currentAlarm.value = { ...row };
  processForm.handler = '';
  processForm.processRecord = '';
  processForm.result = '已解决';
  processVisible.value = true;
};

// 处理当前报警
const handleProcessCurrentAlarm = () => {
  detailsVisible.value = false;
  handleProcessAlarm(currentAlarm.value);
};

// 确认处理报警
const confirmProcessAlarm = () => {
  processFormRef.value.validate().then((result) => {
    if (result === true) {
      confirmLoading.value = true;
      
      setTimeout(() => {
        // 更新报警状态
        const index = alarms.value.findIndex(item => item.id === currentAlarm.value.id);
        if (index !== -1) {
          alarms.value[index] = {
            ...alarms.value[index],
            status: '已处理',
            handler: processForm.handler,
            processRecord: processForm.processRecord,
          };
          
          // 更新当前报警对象（用于详情显示）
          currentAlarm.value = {
            ...currentAlarm.value,
            status: '已处理',
            handler: processForm.handler,
            processRecord: processForm.processRecord,
          };
          
          MessagePlugin.success('报警处理成功');
        }
        
        processVisible.value = false;
        confirmLoading.value = false;
      }, 500);
    }
  }).catch(error => {
    console.log('验证失败:', error);
  });
};

// 生命周期钩子
onMounted(() => {
  // 这里可以添加从API获取报警记录的逻辑
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style scoped>
.alarm-records {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-actions {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.alarm-details {
  margin-bottom: 20px;
}

.alarm-chart {
  margin-top: 24px;
}

.chart-placeholder {
  height: 200px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}

.action-buttons {
  margin-top: 24px;
  text-align: right;
}
</style> 